﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Configuration;

using Happy.Web.Mvc.Utils;
using Happy.Web.Mvc.FileUpload;

namespace Happy.Web.Mvc.ExtJs
{
    /// <summary>
    /// 集成 ExtJs，提供文件上传功能。
    /// </summary>
    public class ExtJsFileUploadController : AjaxController
    {
        private static readonly string _ExtJs_Upload_Files_Relative_Url_Setting_Name = "ExtJs_Upload_Files_Relative_Url";
        private static readonly string _ExtJs_Upload_Files_Relative_Url_Default_Value = "/ExtJs_Upload_Files";
        private static readonly string _ExtJs_Upload_Image_Extension_Reg_Setting_Name = "ExtJs_Upload_Image_Extension_Reg";
        private static readonly string _ExtJs_Upload_Image_Extension_Reg_Url_Default_Value = @"\.[(jpeg)|(jpg)|(gif)|(png)|(bmp)]";

        /// <summary>
        /// 上传附件。
        /// </summary>
        public ActionResult UploadLink(string childDirectory)
        {
            childDirectory = childDirectory ?? "Links";

            var fileUploader = CreateFileUploader(childDirectory);

            return this.Upload(fileUploader);
        }

        /// <summary>
        /// 上传图片。
        /// </summary>
        public ActionResult UploadImage(string childDirectory)
        {
            childDirectory = childDirectory ?? "Images";

            var fileUploader = CreateFileUploader(childDirectory);
            fileUploader.AllowedFileExtensionReg = ConfigurationManager.AppSettings[_ExtJs_Upload_Image_Extension_Reg_Setting_Name] ?? _ExtJs_Upload_Image_Extension_Reg_Url_Default_Value;

            return this.Upload(fileUploader);
        }

        private static FileUploader CreateFileUploader(string childDirectory)
        {
            var uploadFilesRelativeUrl = ConfigurationManager.AppSettings[_ExtJs_Upload_Files_Relative_Url_Setting_Name] ?? _ExtJs_Upload_Files_Relative_Url_Default_Value;

            return new FileUploader(new GuidSavedFileNameProvider(uploadFilesRelativeUrl + "/" + childDirectory));
        }

        private ActionResult Upload(FileUploader fileUploader)
        {
            try
            {
                var fileUploadResult = fileUploader.Upload(this.Request.Files[0]);
                var url = UrlUtil.GetRelativeUrl(fileUploadResult.SavedFileName);

                return this.NewtonsoftJson(new
                {
                    success = true,
                    url
                });
            }
            catch (Exception ex)
            {
                return this.NewtonsoftJson(new
                {
                    success = false,
                    message = ex.Message
                });
            }
        }
    }
}
